GoLang

Explain Defer Keyword in GoLang | Go Programming Tutorial

Explain Defer Keyword in GoLang | Go Programming Tutorial

Explain Defer Keyword in GoLang | Go Programming Tutorial

In this article, you will learn about the defer keyword in the Go Programming Language.

What is the Defer Keyword in GoLang?

In GoLang, defer statements help the execution of the function or method or an anonymous method until the function returns anything. In simple words, the defer function or method call arguments evaluate instantly, but they don’t execute until the function returns. The user can create a deferred function, method, or anonymous function by using the defer keyword.

SYNTAX:

// Function

defer func name_of_func(parameters_list Type) return_type {

 // set of statements

}

//Method

defer func (receiver Type) method_name(parameters_list) {

   // set of statements

}

defer func (parameter_list) (return_type) {

   // set of statements

}()

Example

package main
import "fmt"
 
func multiply(a1, a2 int) int {
 
    res := a1 * a2
    fmt.Println("Result: ", res)
    return 0
}
 
func show() {
    fmt.Println("Hello!, TutorialsLink")
}
 
// Main function
func main() {
    multiply(15, 20)
    defer multiply(20, 54)
 
    // Calling show() function
    show()
}

OUTPUT:

Result: 300

Hello! , TutorialsLink

Result: 1080

Points to be Remembered:

  • In GoLang, many defer statements are allowed in the same program and they are all executed in the Last-In, First-Out(LIFO).
  • In the defer statements, the arguments are evaluated when it is executed, not when it is called.
  • Defer statements are generally used to ensure that the files are closed when their need is over.
Yamini  Sharma

I am working as a professional engineer in "HIghRadius Technologies Pvt. Ltd." Passionate about learning and exploring new technologies. Enthusiast in writing and sharing what I have in my knowledge bucket.